package cn.com.api.service.impl;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.bouncycastle.crypto.io.MacOutputStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.com.api.entity.*;
import cn.com.api.mapper.ApiSmslogMapper;
import cn.com.api.mapper.ApiT_bankcardMapper;
import cn.com.api.mapper.ApiT_browse_historyMapper;
import cn.com.api.mapper.ApiT_memberMapper;
import cn.com.api.mapper.ApiT_member_entrepreneurMapper;
import cn.com.api.mapper.ApiT_orderMapper;
import cn.com.api.mapper.ApiT_shipper_accountMapper;
import cn.com.api.mapper.ApiT_shippingMapper;
import cn.com.api.mapper.ApiT_shop_pay_recordsMapper;
import cn.com.api.mapper.ApiT_user_cash_recordsMapper;
//import cn.com.api.mapper.ApiTmemberMapper;
import cn.com.api.mapper.ApiU_messageMapper;
import cn.com.api.service.ApiT_memberService;
import cn.com.api.service.impl.base.T_memberServiceImplBase;
//import cn.com.pingpp.PingppUtil;
import cn.com.util.*;
import cn.jpush.api.push.model.Message;

/**
 * 
 **/
@Service
public class ApiT_memberServiceImpl extends T_memberServiceImplBase implements ApiT_memberService {
	@Autowired
	private ApiT_memberMapper apiT_memberMapper;
	@Autowired
	private ApiT_shipper_accountMapper apiT_shipper_accountMapper;
	@Autowired
	private ApiT_shippingMapper apiT_shippingMapper;
	@Autowired
	private ApiT_browse_historyMapper apiT_browse_historyMapper;
	@Autowired
	private ApiT_member_entrepreneurMapper apiT_member_entrepreneurMapper;
	@Autowired
	private ApiT_user_cash_recordsMapper apiT_user_cash_recordsMapper;
	@Autowired
	private ApiU_messageMapper apiU_messageMapper;
	@Autowired
	private ApiT_orderMapper apiT_orderMapper;
	@Autowired
	private ApiT_bankcardMapper apiT_bankcardMapper;
	@Autowired
	private ApiT_shop_pay_recordsMapper apiT_shop_pay_recordsMapper;
	@Autowired
	private ApiSmslogMapper apiSmslogMapper;

	@Override
	public List<ApiT_member> findT_membersByType(Integer c_mtype) {
		//
		List<ApiT_member> t_members = apiT_memberMapper.findT_membersByType(c_mtype);
		return t_members;
	}

	// 新建一个配送员账号
	@Override
	@Transactional
	public int insertT_memberShipper(ApiT_member t_member) {
		//
		int ret_I = apiT_memberMapper.insertT_member(t_member);
		//
		ApiT_shipper_account t_shipper_account = new ApiT_shipper_account();

		t_shipper_account.setUser_id(t_member.getC_userid());
		t_shipper_account.setWorking_status("0");
		t_shipper_account.setOrder_cash(BigDecimal.ZERO);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String str_now = sdf.format(new Date());
		t_shipper_account.setReserve_money(t_member.getReserve_money());
		t_shipper_account.setCreate_time(str_now);
		t_shipper_account.setUpdate_time(str_now);
		t_shipper_account.setBank_card(t_member.getBank_card());
		t_shipper_account.setBank_num(t_member.getBank_num());
		t_shipper_account.setID_card(t_member.getID_card());
		t_shipper_account.setHealth_card(t_member.getHealth_card());
		t_shipper_account.setID_num(t_member.getID_num());
		// t_shipper_account.setMoney((double) t_member.getC_money());
		t_shipper_account.setBasic_wage(t_member.getBasic_wage());
		int ret_II = apiT_shipper_accountMapper.insertT_shipper_account(t_shipper_account);
		return ret_I;
	}

	// 编辑配送员
	@Override
	@Transactional
	public int editorT_memberShipper(ApiT_member t_member) {
		int ret_I = apiT_memberMapper.updateT_member(t_member);

		ApiT_shipper_account t_shipper_account = apiT_shipper_accountMapper
				.selectShipperAccountByUid(t_member.getC_userid());
		t_shipper_account.setUser_id(t_member.getC_userid());
		t_shipper_account.setWorking_status("0");
		t_shipper_account.setReserve_money(t_member.getReserve_money());
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String str_now = sdf.format(new Date());
		t_shipper_account.setUpdate_time(str_now);
		t_shipper_account.setBank_card(t_member.getBank_card());
		t_shipper_account.setBank_num(t_member.getBank_num());
		t_shipper_account.setID_card(t_member.getID_card());
		t_shipper_account.setHealth_card(t_member.getHealth_card());
		t_shipper_account.setID_num(t_member.getID_num());
		// t_shipper_account.setMoney((double) t_member.getC_money());
		t_shipper_account.setBasic_wage(t_member.getBasic_wage());
		int ret_II = apiT_shipper_accountMapper.updateT_shipper_account(t_shipper_account);
		return ret_I;
	}

	@Override
	// 根据c_userid查找
	public ApiT_member findT_membersByUserid(String c_userid) {

		return apiT_memberMapper.findT_membersByUserid(c_userid);
	}

	@Override
	// 配送员结算列表
	public List<Finance_balance> shipper_cash_list(PageInfo pageInfo, String status, String date1, String date2) {
		List<Finance_balance> shipper_cashs = new ArrayList<Finance_balance>();
		if (status.equals("3") && (date1 == "" || date1 == null) && (date2 == "" || date2 == null)) {
			List<Finance_balance> shipper_cashs2 = new ArrayList<Finance_balance>();
			return shipper_cashs2;
		} else {
			java.text.DecimalFormat df = new java.text.DecimalFormat("#.00");
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			String d = format.format(new Date());
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(new Date());
			calendar.add(Calendar.DATE, -1);
			Date date = calendar.getTime();
			String date_yesterday = format.format(date);
			if (date2 != null && date2 != "") {
				try {
					Calendar calendar2 = Calendar.getInstance();
					calendar2.setTime(format.parse(date2));
					calendar2.add(Calendar.DATE, 1);
					Date date0 = calendar2.getTime();
					date2 = format.format(date0);
				} catch (ParseException e) {
					e.printStackTrace();
				}
			}

			// 查询所有配送员
			List<ApiT_shipper_account> shippers = apiT_shipper_accountMapper.shipperListPage(pageInfo);
			if (!shippers.isEmpty()) {
				for (ApiT_shipper_account shipper : shippers) {
					Finance_balance shipper_cash = new Finance_balance();
					shipper_cash.setId(shipper.getId());

					shipper_cash.setUser_id(shipper.getUser_id());
					shipper_cash.setReserve_money(shipper.getReserve_money());
					ApiT_member member = apiT_memberMapper.findT_membersByUserid(shipper.getUser_id());
					if (member != null) {
						shipper_cash.setC_tname(member.getC_tname());
					}
					double on_delivery_money = 0;
					double cash_term_money = 0;
					int shipping_num = 0;
					List<ApiT_shipping> shippings = new ArrayList<ApiT_shipping>();
					// 查询配送员时间段之内所有配送订单
					if (status.equals("1")) {
						date1 = d;
						System.out.println("status1_date1:" + date1);
						System.out.println("status1_date2:" + date2);
						shippings = apiT_shippingMapper.bytime_uid(shipper.getUser_id(), status, date1, date2);

					}
					if (status.equals("2")) {
						date1 = date_yesterday;
						System.out.println("status2_date1:" + date1);
						System.out.println("status2_date2:" + date2);
						shippings = apiT_shippingMapper.bytime_uid(shipper.getUser_id(), status, date_yesterday, date2);
					}
					if (status.equals("3") && date1 != "" && date1 != null && date2 != "" && date2 != null) {
						System.out.println("status3_date1:" + date1);
						System.out.println("status3_date2:" + date2);
						shippings = apiT_shippingMapper.bytime_uid(shipper.getUser_id(), status, date1, date2);
					}
					if (!shippings.isEmpty()) {
						for (ApiT_shipping shipping : shippings) {
							on_delivery_money = on_delivery_money + shipping.getOn_delivery_money().doubleValue();
							cash_term_money = cash_term_money + shipping.getCash_term_money().doubleValue();
							shipping_num = shipping_num + 1;
						}
					}
					shipper_cash.setOn_delivery_money(on_delivery_money);
					shipper_cash.setCash_term_money(cash_term_money);
					shipper_cash.setShipping_num(shipping_num);
					shipper_cash.setCash_different((double) 0);
					shipper_cash.setCash_money(Double.parseDouble(df.format(
							shipper.getReserve_money().doubleValue() + on_delivery_money - cash_term_money - 200)));
					shipper_cash.setAll_money(
							shipper.getReserve_money().doubleValue() + on_delivery_money - cash_term_money);
					if (shipper.getBalance_date() != null) {
						shipper_cash.setBalance_date(format.format(shipper.getBalance_date()));
					}
					shipper_cash.setBalance_date(null);
					if (shipper.getReserve_money().intValue() - 200 > 0) {
						shipper_cash.setGive_money(
								Double.parseDouble(df.format(shipper.getReserve_money().doubleValue() - 200)));
					} else {
						shipper_cash.setGive_money((double) 0);
					}
					shipper_cashs.add(shipper_cash);
				}
			}
		}

		return shipper_cashs;
	}

	@Override
	public List<ApiT_member> searchMember(Map<String, Object> conditions, PageInfo pageInfo) {
		return apiT_memberMapper.searchMemberListPage(conditions, pageInfo);
	}

	@Override
	public List<Member_Charge_List> searchMemberChargeList(PageInfo pageInfo, Map<String, Object> conditions) {
		return apiT_memberMapper.searchMemberChargeListPage(pageInfo, conditions);
	}

	@Override
	public List<Member_Charge_List> searchMemberChargeDetailList(PageInfo pageInfo, Map<String, Object> conditions) {
		return apiT_memberMapper.searchMemberChargeDetailListPage(pageInfo, conditions);
	}

	@Override
	public Map<String, Object> shareInfoById(String userid) {
		return apiT_memberMapper.shareInfoById(userid);
	}

	public List<Map<String, Object>> findBrowseHistoryGoods(String cuserid) {
		return apiT_browse_historyMapper.findBrowseHostoryGoods(cuserid);
	}

	public List<ApiT_member> findT_membersByMap(Map<String, Object> conditions) {
		return apiT_memberMapper.findT_membersByMap(conditions);
	}

	@Override
	public ApiT_member getMemberById(String cid) {
		// TODO Auto-generated method stub
		return apiT_memberMapper.getMemberById(cid);
	}

	@Override
	public void updateMemberMoneyByUserId(String userId, BigDecimal money) {
		apiT_memberMapper.updateMemberMoneyByUserId(userId, money);

	}

	@Override
	public boolean findT_membersVerify(Integer type, String user_id) {
		Map<String, Object> map = new HashMap<String, Object>();
		if (type == 2) {
			// 需求为企业主才能发布
			map.put("user_id", user_id);
			map.put("verify_entrepreneur", 1);
			List<Map<String, Object>> list = apiT_member_entrepreneurMapper.findMember_entrepreneursByMap(map);
			if (list.size() >= 1) {
				return true;
			}
		}

		if (type == 1 || type == 0) {
			// 服务和活动,为认证用户即可发布
			map.put("user_id", user_id);
			map.put("verify_idcard", 1);
			List<Map<String, Object>> list = apiT_member_entrepreneurMapper.findMember_infoByMap(map);
			if (list.size() >= 1) {
				return true;
			}
		}
		return false;
	}

	@Override
	public ApiT_member findMemberByCid(String user_id) {
		return apiT_memberMapper.findT_memberById(Integer.parseInt(user_id));
	}

	public List<ApiT_member> getnearlyTransferUser(String user_id, PageInfo pageInfo) throws Exception {
		return apiT_memberMapper.getnearlyTransferUserListPage(user_id, pageInfo);
	}

	// 转账给别人
	@Transactional
	public Map<String, Object> transferMoney(String user_id, String touser_id, String pwd, String money)
			throws Exception {

		Map<String, Object> map = new HashMap<String, Object>();
		ApiT_member apiT_member = apiT_memberMapper.findT_memberById(Integer.valueOf(user_id));
		ApiT_member tomember = apiT_memberMapper.findT_memberById(Integer.valueOf(touser_id));
		if (!Util.isNull(apiT_member) && !Util.isNull(apiT_member.getPay_pwd())) {// 已设置支付密码
			if (apiT_member.getPay_pwd().equals(CipherUtil.generatePassword(pwd))) {
				BigDecimal c_money = apiT_member.getC_money();
				BigDecimal bdmoney = new BigDecimal(money);
				if (c_money.compareTo(bdmoney) >= 0) {
					String nowTimeToString = DateUtil.nowTimeToString();

					ApiT_order t_order = new ApiT_order();
					t_order.setTitles("");
					t_order.setShop_id(user_id);
					t_order.setUser_id(user_id);
					t_order.setName(apiT_member.getC_nick());// 根据userId获取
					t_order.setTel(apiT_member.getC_tel());// 根据userId获取
					t_order.setMobile(apiT_member.getC_mob());// 根据userId获取
					t_order.setEmail(apiT_member.getC_mail());// 根据userId获取
					t_order.setZip(apiT_member.getC_zip());// 根据userId获取
					t_order.setTitles("转账");
					t_order.setBz("转账");

					t_order.setMoney(bdmoney);
					t_order.setAppuser("");
					t_order.setAppdate(nowTimeToString);
					t_order.setEnable(0);// 未删除
					t_order.setZi_status(1);// 已支付
					t_order.setDd_status(2);// 已付款
					t_order.setZf_type("0");
					t_order.setRemainmoney(bdmoney);// 余额 支付方式为0时 插入
					t_order.setSerial(Random.randomStr());
					String orderNum = Utils.getDingDanNo("");
					t_order.setOrdernum(orderNum);
					t_order.setSerialflagno(orderNum);// 订单一起支付标记首个订单号
					t_order.setOrdertype(11);// 转账订单
					t_order.setPaytime(DateUtil.nowTimeToString());

					t_order.setTakegoodstime("");// 收货时间
					t_order.setCancelreason("");// 订单取消原因
					t_order.setIs_quan(0);// 是否使用优惠券
											// 0-未使用
											// 1-使用
					t_order.setPaymoney(bdmoney);// 优惠后的金额
					// 插入订单数据
					apiT_orderMapper.T_orderInsertion(t_order);

					// 扣除金额
					apiT_member.setC_money(c_money.subtract(bdmoney));
					apiT_memberMapper.updateT_member(apiT_member);

					ApiT_user_cash_records apiT_user_cash_records = new ApiT_user_cash_records();
					apiT_user_cash_records.setCreate_time(nowTimeToString);
					apiT_user_cash_records.setMoney(bdmoney);
					apiT_user_cash_records.setOrder_id(t_order.getRid() + "");
					apiT_user_cash_records.setPay_type(0);
					apiT_user_cash_records.setPay_type_desc("0");
					apiT_user_cash_records.setCate_type(7);
					apiT_user_cash_records.setIs_receive(0);
					apiT_user_cash_records.setRemark("转账给 " + tomember.getC_nick());

					// 根据是否是充值订单判断是收入还是支出
					apiT_user_cash_records.setProcess_type(1);
					apiT_user_cash_records.setIs_receive(0);// 还未领取
					apiT_user_cash_records.setConn_id(tomember.getC_id() + "");
					apiT_user_cash_records.setUser_id(apiT_member.getC_id() + "");
					apiT_user_cash_recordsMapper.T_user_cash_recordsInsertion(apiT_user_cash_records);

					// 加入消息中
					// ApiU_message apiU_message = new ApiU_message();
					// apiU_message.setAdd_time(nowTimeToString);
					// apiU_message.setContent("您转给" + tomember.getC_nick()
					// + " " + bdmoney + "元");
					// apiU_message.setUser_id(apiT_member.getC_id());
					// apiU_message.setType(10);
					// apiU_message.setTitle("转账");
					// apiU_message.setConn_id(Integer.valueOf(tomember.getC_id()));
					// apiU_message.setIs_read(0);
					// apiU_messageMapper.insertU_message(apiU_message);

					// ********************
					// ********************
					map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
					map.put(Utils.MESSAGE, "转账成功");
					map.put(Utils.DATAS, apiT_user_cash_records.getRecord_id());
				} else {
					map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
					map.put(Utils.MESSAGE, "账户余额不足");
				}
			} else {
				map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
				map.put(Utils.MESSAGE, "支付密码不正确");
			}
		} else {
			map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
			map.put(Utils.MESSAGE, "请先设置支付密码");
		}
		return map;
	}

	// 生成充值订单
	@Transactional(rollbackFor = Exception.class)
	public Map<String, Object> depositorder(String user_id, String money) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		ApiT_order t_order = new ApiT_order();
		t_order.setTitles("充值订单");
		t_order.setShop_id("");
		t_order.setUser_id(user_id);
		t_order.setPeisong("");// 1 物流 2 自提
		ApiT_member apiT_member = apiT_memberMapper.findT_memberById(Integer.valueOf(user_id));
		if (apiT_member != null) {
			t_order.setName(apiT_member.getC_cname());// 根据userId获取
			t_order.setTel(apiT_member.getC_tel());// 根据userId获取
			t_order.setMobile("");// 根据userId获取
			t_order.setEmail(apiT_member.getC_mail());// 根据userId获取
			t_order.setZip(apiT_member.getC_zip());// 根据userId获取
		}
		t_order.setAddress("");
		t_order.setDtime("");// 送达时间 //待定
		t_order.setBz("");

		t_order.setMoney(new BigDecimal(money));
		t_order.setAppuser("");
		t_order.setAppdate(DateUtil.nowTimeToString());
		t_order.setRip("");
		t_order.setBz("充值订单");
		t_order.setPaymoney(new BigDecimal(money));
		t_order.setEnable(1);// 未完成订单
		t_order.setZi_status(0);// 未支付
		t_order.setDd_status(1);// 未支付
		t_order.setOrdertype(1);// 充值订单
		String dingDanNo = Utils.getDingDanNo("");
		t_order.setOrdernum(dingDanNo);
		t_order.setSerialflagno(dingDanNo);
		apiT_orderMapper.T_orderInsertion(t_order);
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("order_no", dingDanNo);
		result.put("amount", t_order.getMoney());
		result.put("subject", "充值订单");
		result.put("order_desc", "充值订单");
		map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
		map.put(Utils.MESSAGE, "操作成功");
		map.put(Utils.DATAS, result);
		return map;
	}

	// 生成转账订单
	@Transactional(rollbackFor = Exception.class)
	public Map<String, Object> createtransferorder(String user_id, String touser_id, String createType, String money)
			throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		ApiT_order t_order = new ApiT_order();
		t_order.setTitles("转账订单");
		t_order.setShop_id("");
		t_order.setUser_id(user_id);
		t_order.setPeisong("");// 1 物流 2 自提
		ApiT_member apiT_member = apiT_memberMapper.findT_memberById(Integer.valueOf(user_id));
		if (apiT_member != null) {
			t_order.setName(apiT_member.getC_cname());// 根据userId获取
			t_order.setTel(apiT_member.getC_tel());// 根据userId获取
			t_order.setMobile("");// 根据userId获取
			t_order.setEmail(apiT_member.getC_mail());// 根据userId获取
			t_order.setZip(apiT_member.getC_zip());// 根据userId获取
		}
		t_order.setAddress("");
		t_order.setDtime("");// 送达时间 //待定

		t_order.setMoney(new BigDecimal(money));
		t_order.setAppuser("");
		t_order.setAppdate(DateUtil.nowTimeToString());
		t_order.setRip("");
		t_order.setBz("转账订单");
		t_order.setPaymoney(new BigDecimal(money));
		t_order.setEnable(1);// 未完成订单
		t_order.setZi_status(0);// 未支付
		t_order.setDd_status(1);// 未支付
		t_order.setOrdertype(11);// 转账订单
		String dingDanNo = Utils.getDingDanNo("");
		t_order.setOrdernum(dingDanNo);
		t_order.setSerialflagno(dingDanNo);
		t_order.setExt_1(touser_id);// 转账给某用户的id
		t_order.setExt_2(createType);// 转账时是否需要对方确认
		apiT_orderMapper.T_orderInsertion(t_order);
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("order_no", dingDanNo);
		result.put("amount", t_order.getMoney());
		result.put("subject", "转账订单");
		result.put("order_desc", "转账订单");
		map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
		map.put(Utils.MESSAGE, "操作成功");
		map.put(Utils.DATAS, result);
		return map;
	}

	// 提现
	@Transactional
	public Map<String, Object> withdrawCash(String user_id, String bankcard_id, String money, String pwd)
			throws Exception {

		Map<String, Object> map = new HashMap<String, Object>();
		ApiT_member apiT_member = apiT_memberMapper.findT_memberById(Integer.valueOf(user_id));
		if (!Util.isNull(apiT_member) && !Util.isNull(apiT_member.getPay_pwd())) {// 已设置支付密码
			if (apiT_member.getPay_pwd().equals(CipherUtil.generatePassword(pwd))) {
				BigDecimal c_money = apiT_member.getC_money();
				BigDecimal bdmoney = new BigDecimal(money);
				if (c_money.compareTo(bdmoney) >= 0) {
					ApiT_bankcard apiT_bankcard = apiT_bankcardMapper.findT_bankcardById(Integer.valueOf(bankcard_id));

					String nowTimeToString = DateUtil.nowTimeToString();
					apiT_member.setC_money(c_money.subtract(bdmoney));
					apiT_memberMapper.updateT_member(apiT_member);

					// 插入提现记录
					ApiT_shops_pay_records apiT_shops_pay_records = new ApiT_shops_pay_records();
					apiT_shops_pay_records.setShop_id(Integer.valueOf(user_id));
					apiT_shops_pay_records.setBank_name(apiT_bankcard.getOpeningbank());
					apiT_shops_pay_records.setBank_num(apiT_bankcard.getCardno());
					apiT_shops_pay_records.setCardname(apiT_bankcard.getCardname());
					apiT_shops_pay_records.setPhone(apiT_bankcard.getPhone());
					apiT_shops_pay_records.setCredentialsno(apiT_bankcard.getCredentialsno());
					apiT_shop_pay_recordsMapper.insertT_shop_pay_record(apiT_shops_pay_records);

					// 用户金额变动信息
					ApiT_user_cash_records apiT_user_cash_records = new ApiT_user_cash_records();
					apiT_user_cash_records.setCreate_time(nowTimeToString);
					apiT_user_cash_records.setMoney(bdmoney);
					apiT_user_cash_records.setOrder_id("");
					apiT_user_cash_records.setRemark("提现");
					apiT_user_cash_records.setPay_type(0);
					apiT_user_cash_records.setPay_type_desc("提现");
					apiT_user_cash_records.setCate_type(8);
					apiT_user_cash_records.setRemark("提现");
					// 根据是否是充值订单判断是收入还是支出
					apiT_user_cash_records.setProcess_type(1);
					apiT_user_cash_records.setConn_id("");
					apiT_user_cash_records.setUser_id(user_id);
					apiT_user_cash_recordsMapper.T_user_cash_recordsInsertion(apiT_user_cash_records);

					// 加入消息中
					ApiU_message apiU_message = new ApiU_message();
					apiU_message.setAdd_time(nowTimeToString);
					apiU_message.setContent("您提现了" + bdmoney + "元");
					apiU_message.setUser_id(apiT_member.getC_id() + "");
					apiU_message.setType(10);
					apiU_message.setTitle("转账");
					apiU_message.setConn_id(null);
					apiU_message.setIs_read(0);
					apiU_messageMapper.insertU_message(apiU_message);
					// messagelist.add(apiU_message);
					// apiU_messageMapper.insertmessageList(messagelist);
					map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
					map.put(Utils.MESSAGE, "提现成功");
				} else {
					map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
					map.put(Utils.MESSAGE, "账户余额不足");
				}
			} else {
				map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
				map.put(Utils.MESSAGE, "支付密码不正确");
			}
		} else {
			map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
			map.put(Utils.MESSAGE, "请先设置支付密码");
		}
		return map;

	}

	// 接受转账
	public Map<String, Object> receiveMoney(String user_id, String record_id) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		ApiT_member apiT_member = apiT_memberMapper.findT_memberById(Integer.valueOf(user_id));

		ApiT_user_cash_records apiT_user_cash_records = apiT_user_cash_recordsMapper
				.findT_user_cash_recordsById(Integer.valueOf(record_id));
		ApiT_member fromuser = apiT_memberMapper.findT_memberById(Integer.valueOf(apiT_user_cash_records.getUser_id()));
		if (apiT_user_cash_records.getIs_receive() == 0) {// 可以领取

			if (apiT_user_cash_records.getConn_id().equals(user_id + "")) {
				String nowTimeToString = DateUtil.nowTimeToString();
				apiT_user_cash_records.setIs_receive(1);
				apiT_user_cash_recordsMapper.updateT_user_cash_records(apiT_user_cash_records);
				// 更新金额
				apiT_member.setC_money(apiT_member.getC_money().add(apiT_user_cash_records.getMoney()));
				apiT_memberMapper.updateT_member(apiT_member);
				//
				ApiT_user_cash_records apiT_user_cash_records2 = new ApiT_user_cash_records();
				apiT_user_cash_records2.setCreate_time(nowTimeToString);
				apiT_user_cash_records2.setMoney(apiT_user_cash_records.getMoney());
				apiT_user_cash_records2.setOrder_id(apiT_user_cash_records.getOrder_id());
				apiT_user_cash_records2.setRemark("转账");
				apiT_user_cash_records2.setPay_type(0);
				apiT_user_cash_records2.setPay_type_desc("0");
				apiT_user_cash_records2.setCate_type(7);
				apiT_user_cash_records2.setRemark(fromuser.getC_nick() + " 给我转账");
				// 根据是否是充值订单判断是收入还是支出
				apiT_user_cash_records2.setProcess_type(0);
				apiT_user_cash_records2.setIs_receive(1);// 还未领取
				apiT_user_cash_records2.setConn_id(fromuser.getC_id() + "");
				apiT_user_cash_records2.setUser_id(user_id);
				apiT_user_cash_recordsMapper.T_user_cash_recordsInsertion(apiT_user_cash_records2);

				// 加入消息中
				ApiU_message apiU_message = new ApiU_message();
				apiU_message.setAdd_time(nowTimeToString);
				apiU_message.setContent(fromuser.getC_nick() + " 给您转账了" + apiT_user_cash_records.getMoney() + "元");
				apiU_message.setUser_id(user_id);
				apiU_message.setType(10);
				apiU_message.setTitle("转账");
				apiU_message.setConn_id(Integer.valueOf(fromuser.getC_id()));
				apiU_message.setIs_read(0);
				apiU_messageMapper.insertU_message(apiU_message);
				map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
				map.put(Utils.MESSAGE, "领取成功");
			} else {
				map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
				map.put(Utils.MESSAGE, "用户不正确");
			}
		} else if (apiT_user_cash_records.getIs_receive() == 1) {
			map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
			map.put(Utils.MESSAGE, "已领取");
		} else {
			map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
			map.put(Utils.MESSAGE, "已过期");
		}
		return map;
	}

	// 生成付款码
	@Transactional
	public Map<String, Object> createPayQRcode(String user_id) throws Exception {

		Map<String, Object> map = new HashMap<String, Object>();
		// 生成预付款订单。金额为0
		ApiT_order t_order = new ApiT_order();
		t_order.setTitles("转账订单");
		t_order.setShop_id("");
		t_order.setUser_id(user_id);
		t_order.setPeisong("");// 1 物流 2 自提
		ApiT_member apiT_member = apiT_memberMapper.findT_memberById(Integer.valueOf(user_id));
		if (apiT_member != null) {
			t_order.setName(apiT_member.getC_cname());// 根据userId获取
			t_order.setTel(apiT_member.getC_tel());// 根据userId获取
			t_order.setMobile("");// 根据userId获取
			t_order.setEmail(apiT_member.getC_mail());// 根据userId获取
			t_order.setZip(apiT_member.getC_zip());// 根据userId获取
		}
		t_order.setAddress("");
		t_order.setDtime("");// 送达时间 //待定

		t_order.setMoney(BigDecimal.ZERO);
		t_order.setAppuser("");
		t_order.setAppdate(DateUtil.nowTimeToString());
		t_order.setRip("");
		t_order.setBz("转账订单");
		t_order.setPaymoney(BigDecimal.ZERO);
		t_order.setEnable(1);// 未完成订单
		t_order.setZi_status(0);// 未支付
		t_order.setDd_status(1);// 未支付
		t_order.setOrdertype(11);// 转账订单
		String dingDanNo = Utils.getDingDanNo("");
		t_order.setOrdernum(dingDanNo);
		t_order.setSerialflagno(dingDanNo);
		t_order.setExt_2("0");// 转账时是否需要对方确认
		apiT_orderMapper.T_orderInsertion(t_order);
		// 预支付二维码地址
		String payQRcodeurl = setPayQRcode(dingDanNo, user_id);
		String qrcodeinfo = QRCodeUtils.baseUrl + "/partner/sq-ziliao.html?code=" + "4:" + dingDanNo + ":" + user_id;
		map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
		map.put(Utils.MESSAGE, "操作成功");
		map.put(Utils.DATAS, payQRcodeurl);
		map.put("ordernum", dingDanNo);
		map.put("qrcodeinfo", qrcodeinfo);
		return map;

	}

	public Map<String, Object> scanReceiveMoney(String user_id, String money, String ordernum) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		ApiT_order apiT_order = apiT_orderMapper.findT_orderByOrderNum(ordernum);
		if (apiT_order.getMoney() == BigDecimal.ZERO) {// 还没有人扫，可以使用
			apiT_order.setExt_1(user_id);
			apiT_order.setMoney(new BigDecimal(money));
			apiT_order.setPaymoney(new BigDecimal(money));
			apiT_orderMapper.updateT_order(apiT_order);
			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			map.put(Utils.MESSAGE, "扫码成功");
		} else {// 该付款码已被扫，无法使用
			map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
			map.put(Utils.MESSAGE, "付款码已被扫");
		}
		return map;

	}

	@Transactional
	public Map<String, Object> checkPayQRCodeOrder(String ordernum) throws Exception {

		Map<String, Object> map = new HashMap<String, Object>();
		ApiT_order apiT_order = apiT_orderMapper.findT_orderByOrderNum(ordernum);
		if (apiT_order.getMoney() != BigDecimal.ZERO && !"".equals(apiT_order.getExt_1())
				&& apiT_order.getZi_status() == 0) {// 该付款码已经被别人扫了,请去支付。
			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			map.put(Utils.MESSAGE, "付款码已被扫");
			map.put(Utils.DATAS, apiT_order);
		} else if (apiT_order.getMoney() == BigDecimal.ZERO && "".equals(apiT_order.getExt_1())
				&& apiT_order.getZi_status() == 0) {//
			map.put(Utils.RESULT, Utils.RESULT_RC_CHECK_FAIL);
			map.put(Utils.MESSAGE, "付款码未被扫");
		} else if (apiT_order.getMoney() != BigDecimal.ZERO && !"".equals(apiT_order.getExt_1())
				&& apiT_order.getZi_status() == 0) {// 该付款码已被扫，无法使用
			map.put(Utils.RESULT, Utils.RESULT_RC_EXIST);
			map.put(Utils.MESSAGE, "付款码已失效");
		} else {// 该付款码已被扫，无法使用
			map.put(Utils.RESULT, Utils.RESULT_RC_EXIST);
			map.put(Utils.MESSAGE, "付款码已失效");
		}
		return map;

	}

	private String setPayQRcode(String info, String user_id) {
		String retCode = "";
		try {
			String qrCodeInfo = QRCodeUtils.baseUrl + "/partner/sq-ziliao.html?code=" + "4:" + info + ":" + user_id;
			retCode = QRCodeUtils.createQrCode(qrCodeInfo, 300);
			return retCode;
		} catch (Exception e) {
			e.printStackTrace();
			return retCode;
		}
	}

}
